package GUI;

import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.ListSelectionModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import ControlLayer.*;
import ModelLayer.Betaling;
import ModelLayer.Forestilling;
import ModelLayer.Salg;
import ModelLayer.SalgSaede;

import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JLabel;

public class Mainmenu implements ListSelectionListener {

	private JFrame frame;
	private ForestillingsCtr fctr;
	private ArrayList<Forestilling> flist;
	private ArrayList<ForestillingTableModel> forestillingslist;
	private JComboBox<String> comboBox;
	private JTable table;
	private JLabel lblTitel;
	private JLabel lblNewLabel;
	private JLabel lblSluttid;
	private JLabel lblNewLabel_1;
	private JLabel lblBestlit;
	private JLabel lblNewLabel_2;
	private JLabel lblSal;
	private JLabel lblVlgDato;
	private DateFormat dateFormat;
	private Date date;
	private ArrayList<Forestilling> alleForestillingerlist;
	private ArrayList<String> datoer;
	private ArrayList<SalgSaede> allSS;
	private SalgsCtr salgCtr;

	/**
	 * Create the application.
	 */
	public Mainmenu() {
		dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		date = new Date();
		salgCtr = new SalgsCtr();
		initialize();
		if(datoer.size() > 0)
		{
			comboBox.setSelectedIndex(0);
		}
		frame.setVisible(true);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("Main");
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowActivated(WindowEvent e) {


			}
		});
		frame.setBounds(100, 100, 892, 549);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		frame.setResizable(false);

		comboBoAndTable();
	}

	private void comboBoAndTable()
	{
		fctr = new ForestillingsCtr();
		getDateInCombobox();
		comboBox.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				findForestillinger();
			}
		});	
		comboBox.setBounds(107, 13, 132, 22);

		frame.getContentPane().add(comboBox);

		table = new JTable();
		table.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent e){
				if (e.getClickCount() == 2)
				{
					//when double clicked, opens the specific forestilling in a new Reservation window
					int i = table.getSelectedRow();
					Forestilling f = fctr.findForestilling(forestillingslist.get(i).getId());
					Reservation res = new Reservation(f);
					frame.dispose();	         
				}
			}
		});
		table.setBounds(12, 77, 862, 375);
		frame.getContentPane().add(table);
		ListSelectionModel listMod = table.getSelectionModel();
		listMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listMod.addListSelectionListener(this);


		//button to open the OpretForestilling GUI as a pop up.
		JButton btnOpretForestilling = new JButton("Opret Forestilling");
		btnOpretForestilling.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				OpretForestilling opretforestilling = new OpretForestilling();
			}
		});
		btnOpretForestilling.setBounds(720, 478, 154, 25);
		frame.getContentPane().add(btnOpretForestilling);

		JButton btnOpretFilm = new JButton("Opret Film");
		btnOpretFilm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				OpretFilm of = new OpretFilm();
			}
		});
		btnOpretFilm.setBounds(576, 478, 132, 25);
		frame.getContentPane().add(btnOpretFilm);


		createLabels();

	}

	private void createLabels()
	{
		lblTitel = new JLabel("Titel:");
		lblTitel.setBounds(55, 48, 56, 16);
		frame.getContentPane().add(lblTitel);

		lblNewLabel = new JLabel("Starttid:");
		lblNewLabel.setBounds(173, 48, 56, 16);
		frame.getContentPane().add(lblNewLabel);

		lblSluttid = new JLabel("Sluttid:");
		lblSluttid.setBounds(301, 48, 56, 16);
		frame.getContentPane().add(lblSluttid);

		lblNewLabel_1 = new JLabel("Solgt:");
		lblNewLabel_1.setBounds(420, 48, 56, 16);
		frame.getContentPane().add(lblNewLabel_1);

		lblBestlit = new JLabel("Bestlit:");
		lblBestlit.setBounds(539, 48, 56, 16);
		frame.getContentPane().add(lblBestlit);

		lblNewLabel_2 = new JLabel("Ledige:");
		lblNewLabel_2.setBounds(658, 48, 42, 16);
		frame.getContentPane().add(lblNewLabel_2);

		lblSal = new JLabel("Sal:");
		lblSal.setBounds(783, 48, 56, 16);
		frame.getContentPane().add(lblSal);

		lblVlgDato = new JLabel("V\u00E6lg Dato:");
		lblVlgDato.setBounds(12, 16, 99, 16);
		frame.getContentPane().add(lblVlgDato);
	}


	private void getDateInCombobox()
	{
		comboBox = new JComboBox<String>();
		datoer = new ArrayList<String>();

		//Using 2 arraylist of all Forestilling, so i can iterate over 1 arraylist
		//while deleting specific Forestilling from the other arrayList
		flist = fctr.getAllForestilling();
		alleForestillingerlist = new ArrayList<Forestilling>();

		//For loop, removes all forestilling that is older than the current date.
		for(Forestilling f : flist)
		{
			String datoYear = f.getFremvisningsDato().substring(0, 4);
			String datoHour = f.getFremvisningsDato().substring(5, 7);
			String datoMin = f.getFremvisningsDato().substring(8);
			String finalDate = datoYear + datoHour + datoMin;
			String newYear = dateFormat.format(date).substring(0, 4);
			String newHour = dateFormat.format(date).substring(5, 7);
			String newMin = dateFormat.format(date).substring(8);
			String finalNewDate = newYear + newHour + newMin;
			if((Integer.parseInt(finalDate) - Integer.parseInt(finalNewDate)) >= 0)
			{
				alleForestillingerlist.add(f);
			}
		}
		//For loop which purpose is to add all Dates in an arrayList
		for(Forestilling f : alleForestillingerlist)
		{
			datoer.add(f.getFremvisningsDato().toString());
		}
		removeDuplicates(datoer);
		Collections.sort(datoer);
		//For loop that adds the remaining dates in the combobox
		for(String dato : datoer)
		{
			comboBox.addItem(dato);
		}
	}
	
	/**
	 * Method used to create table, by finding Forestillinger
	 */
	private void findForestillinger()
	{
		fctr = new ForestillingsCtr();
		allSS = salgCtr.getAllSalgSaede();
		forestillingslist = new ArrayList<ForestillingTableModel>();
		//Foreach which finds the forestilling for the selected date in the combobox
		for(Forestilling f : alleForestillingerlist)
		{
			if(f.getFremvisningsDato().equals(comboBox.getSelectedItem().toString()))
			{
				int bestilt = 0;
				int solgt = 0;
				int ledige = 0;
				Betaling b = new Betaling();
				for(SalgSaede ss : allSS)
				{
					Salg s = salgCtr.findSalg(ss.getSalg().getSalgId());
					if(s.getForestilling().getForestillingId() == f.getForestillingId())
					{
						b = salgCtr.findBetaling(s.getSalgId());
						if(b.getBetalingsStatus())
						{
							solgt++;
						}
						if(!b.getBetalingsStatus())
						{
							bestilt++;
						}
					}
				}
				ledige = ((f.getSal().getAntalPladser() - solgt) - bestilt);
				//System.out.println(bestilt + " " + ledige + " " + solgt);
				ForestillingTableModel forestilling = new ForestillingTableModel(f.getFilm().getTitel(), f.getStart(), f.getSlut(), solgt, bestilt, ledige, f.getSal().getSalNr(), f.getForestillingId());
				forestillingslist.add(forestilling);				
			}
		}
		//End foreach
		ForestillingModel forModel = new ForestillingModel();
		forModel.setData(forestillingslist);

		//forModel.setData(forestillingslist); //adds the forestilling that were found in the foreach to the table

		table.setModel(forModel);
		frame.setVisible(true);
	}


	@Override
	public void valueChanged(ListSelectionEvent e) {

	}

	private void removeDuplicates(ArrayList<String> list)  
	{  
		Set<String> uniqueEntries = new TreeSet<String>();  
		for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) {  
			String element = iter.next();  
			if (!uniqueEntries.add(element)) // if current element is a duplicate,  
				iter.remove();                 // remove it  
		}  
	} 
}
